<?php
require 'db.php';

// 获取搜索关键字
$search = isset($_GET['search']) ? $_GET['search'] : '';

// 查询已发布的文章
$sql_articles = "SELECT a.id, a.title, a.content, u.username AS author_name, a.created_at
                 FROM articles a
                 JOIN users u ON a.author = u.id
                 WHERE a.status = 'approved'";

if ($search) {
    $sql_articles .= " AND a.title LIKE ?";
}

$stmt_articles = $conn->prepare($sql_articles);
if ($search) {
    $search_param = '%' . $search . '%';
    $stmt_articles->bind_param('s', $search_param);
}

$stmt_articles->execute();
$result_articles = $stmt_articles->get_result();

$articles = [];
if ($result_articles->num_rows > 0) {
    while($row = $result_articles->fetch_assoc()) {
        $articles[] = $row;
    }
}

// 查询公告数据
$sql_announcements = "SELECT * FROM announcements ORDER BY created_at DESC";
$result_announcements = $conn->query($sql_announcements);

$announcements = [];
if ($result_announcements->num_rows > 0) {
    while ($row = $result_announcements->fetch_assoc()) {
        $announcements[] = array(
            'id' => $row['id'],
            'title' => $row['title'],
            'content' => $row['content'],
            'created_at' => $row['created_at']
        );
    }
}

// 返回整合后的数据
echo json_encode(array('articles' => $articles, 'announcements' => $announcements));

// 关闭数据库连接
$conn->close();
?>